class HomeScene extends BaseScene {
	public musicBtn: eui.Image; //游戏声音按钮
	
	private titleLbll:eui.Label;
	private jumpIcon:eui.Image;
	private tipsLbl:eui.Label;

	public helpButton: eui.Image; //前往抽奖,打开客服
	public moreGameBtn: eui.Image; //更多游戏
	public shareBtn: eui.Image; // 分享

	public startBtn: eui.Button; //开始游戏

	public ranklistBtn: eui.Label; //排行榜
	public groupRanklistBtn: eui.Label; //群排行
	private adList:Array<any> = [];
	private currentAdIndex:number=0;
	private versionLbl:eui.Label;
	

	//构造器
	public constructor(index: number = GameConfig.uiIndex.home) {
		super(index);
		this.skinName = "HomeSceneSkin";
		this.loadInitData(); // 初始化数据
		// 第一次启动时主动调用一次
		this.updateSound();
		this.jumpIcon.visible = false;
		this.versionLbl.visible = false;
		this.versionLbl.text = "v"+GameConfig.versionStr+"-"+GameConfig.version+":"+UserData.id;
		if(UserData.id == 1){
			this.versionLbl.visible = true;
		}
		if(UserData.is_verify){
			this.helpButton.visible = false;
			this.moreGameBtn.x = 136;
		}else{
			this.moreGameBtn.x = (GameConfig.stageWidth-this.moreGameBtn.width)/2;
		}

	}
	public viewWillAppear(){
        super.viewWillAppear();
        GameConfig.showBannerAd();
		GameConfig.requestAdList(()=>{
			GameConfig.changeCurrentAd(()=>{
				this.updateAdView();
			});
		});

    }
    public viewWillDisAppear(){
        super.viewWillDisAppear();
        GameConfig.hideBannerAd();
    }

	//重载
	public onChildrenCreated() {
		super.onChildrenCreated();
		this.showGroupRank();
		this.requestUserInfo();
		
	}
	
	private updateAdView(){
		if(!UserData.is_verify && GameConfig.currentAd){
			egret.Tween.removeTweens(this.jumpIcon);
			this.jumpIcon.rotation = 0;
			this.jumpIcon.visible = true;
			this.jumpIcon.source = GameConfig.currentAd.icon;
			egret.Tween.removeTweens(this.jumpIcon);
			egret.Tween.get(this.jumpIcon, { loop: true }).wait(1200).to({ rotation: 8 }, 100).to({ rotation: -8 }, 200).to({ rotation: 0 }, 100);
		}else{
			this.jumpIcon.visible = false;
		}
	}
	private jumpAd(){
		if(!GameConfig.currentAd){
			return;
		}
		let ad = GameConfig.currentAd;
		egret.setTimeout(()=>{
			GameConfig.changeCurrentAd(()=>{
				this.updateAdView();
			});
		},this,2000);
		this.requestAdCpc(ad);
		if(ad.appid){
			let param = {appId:ad.appid};
			if(ad.path){
				param["path"] = ad.path;
			}
			if(ad.envVersion){
				param["envVersion"] = ad.envVersion;
			}
			if(ad.extraData){
				param["extraData"] = ad.extraData;
			}
			param["complete"] = this.jumpAdComplete.bind(this);
			
			platform.callPlatformMethod("navigateToMiniProgram",param);
		}else{
			let image = ad.previewImage;
			if(!image){
				image = ad.image;
			}
			platform.previewImage({ urls: [image]});
		}
	}
	private jumpAdComplete(res){
		if(Utils.callWXSuccess(res)){
		}else{
			
			let ad = GameConfig.currentAd;
			let image = ad.previewImage;
			if(!image){
				image = ad.image;
			}
			platform.previewImage({ urls: [image]});
		}
	}
	private requestAdCpc(ad:any){
		let param = {
						user_id:UserData.id,
						ad_appid:ad.appid,
						on_appid:GameConfig.appid
					};
		App.HttpRequestManager.request(NetConstants.AD_CPC, param, (res)=>{
			console.log("requestAdCpc-",res);
		});
	}
	private requestUserInfo(){
		 App.HttpRequestManager.request(NetConstants.GET_INFO, "", this.responseUserInfo.bind(this),egret.HttpMethod.GET);
	}
	private responseUserInfo(res){
		if (res.statusCode == 200 && res.data.code == 0) {
            UserData.saveUserInfo(res.data.data);
        } else {

        }
	}
	
	// game重新可见时根据条件显示群排行榜
	private showGroupRank(){
		// 有shareTicket并且1044：带shareTicket的小程序卡片
		if(GameConfig.shareTicket && GameConfig.showGroupRank && GameConfig.query){
			let from = GameConfig.query.from;
			if(GameConfig.shareFrom.homePageGroup2Share == from || GameConfig.shareFrom.rankListPageSeeGroup2Share == from){
				let indexLen = App.UiManager.indexList.length;
				if(indexLen>0 && App.UiManager.indexList[indexLen-1] == this.index){
					App.EventManager.dispatchEvent(GameConstants.UI_ADD_TO_PARENT, GameConfig.uiIndex.groupRankList);
				}
			}
			GameConfig.showGroupRank = false;
			
		}
	}
	//添加监听 
	public addListener() {
		super.addListener();
		//本页
		this.musicBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.switchMusicBtn, this);

		this.helpButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.openCustomerService, this);
		this.moreGameBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.showMoreGameImage, this);
		this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.shareGame, this);

		//this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);
		ViewUtils.addTapEvent(this.startBtn,this.startGame,this,{scaleX:0.9,scaleY:0.9});

		this.ranklistBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ranklist, this);
		this.groupRanklistBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.groupRanklist, this);

		// 在当前页面存在中间离开小游戏然后再进入的情况
		App.EventManager.addEventListener(GameConstants.GAME_ACTIVE,this.showGroupRank,this);
		// 展示推荐游戏
		this.jumpIcon.addEventListener(egret.TouchEvent.TOUCH_TAP, this.jumpAd, this);
		
	}

	//移除监听 
	public removeListener() {
		super.removeListener();
		this.musicBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.switchMusicBtn, this);

		this.helpButton.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.openCustomerService, this);
		this.moreGameBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.showMoreGameImage, this);
		this.shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.shareGame, this);
		
		ViewUtils.removeTapEvent(this.startBtn,this);
		//this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.startGame, this);

		this.ranklistBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.ranklist, this);
		this.groupRanklistBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.groupRanklist, this);

		App.EventManager.removeEventListener(GameConstants.GAME_ACTIVE,this.showGroupRank,this);
		// 展示推荐游戏
		this.jumpIcon.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.jumpAd, this);
	}

	//=================以下为自定义方法======================
	private loadInitData() {
		// 设置客服按钮的展示
		// if(UserData.customer.show){
		// 	this.helpButton.visible = true;
		// }else{
		// 	this.helpButton.visible = false;
		// }
		this.tipsLbl.text = "已冲到"+UserData.highest_score+"层";
		App.HttpRequestManager.request(NetConstants.GAME_CONFIG, {}, this.responseGameConfig.bind(this), egret.HttpMethod.GET);
	}
	/**
	 * 请求配置信息
	 */
	private responseGameConfig(res){
		if(res && res.statusCode == 200 && res.data.code == 0){
			UserData.saveConfig(res.data.data);
		}else{

		}
	}

	//游戏声音按钮
	private switchMusicBtn() {
		UserData.musicEnabled = !UserData.musicEnabled;
		// 音效设置持久化保存
		UserData.save2Local();
		this.updateSound(true);
	}

	/**
	 * 切换音效设置
	 */
	private updateSound(fromChange:boolean=false)
	{
		if(UserData.musicEnabled){
			this.musicBtn.source = "soundOpened_png";
			if(fromChange){
				TipsUtils.showTipsDownToUp("已开启声音");
			}
			
			SoundManager.playBgMusic();
		}else{
			this.musicBtn.source = "soundClosed_png";
			if(fromChange){
				TipsUtils.showTipsDownToUp("已关闭声音");
			}
			SoundManager.stopBgMusic();
		}
	}

	//客服消息
	private openCustomerService() {
		// 2.0.3后才能进入客服
		if(StringUtil.sdkVersionCompare(GameConfig.SDKVersion,"2.0.3")){
			platform.openCustomerServiceConversation({
				sessionFrom:"customService"
			});
			
		}
	}
	private openCustomerServiceSuccess(res)
	{

	}
	private openCustomerServiceFail(err){

	}


	/**
	 * 更多游戏，展示游戏盒子
	 */
	private showMoreGameImage() {
		this.requestAdCpc(UserData.more_game.wxapp);
		if(!UserData.more_game.isjump && !StringUtil.sdkVersionCompare(GameConfig.SDKVersion,"2.2.0")){
			let image = UserData.more_game.image;
			if(!image){
				image = UserData.more_game.preview_image;
			}
			platform.previewImage({ urls: [image] });
		}else{
			if(UserData.more_game.wxapp.appid){
				let param = {appId:UserData.more_game.wxapp.appid};
				if(UserData.more_game.wxapp.path){
					param["path"] = UserData.more_game.wxapp.path;
				}
				
				if(UserData.more_game.wxapp.extraData){
					param["extraData"] = UserData.more_game.wxapp.extraData;
				}
				param["complete"] = this.moreGameComplete.bind(this);
				
				platform.callPlatformMethod("navigateToMiniProgram",param);
			}else{
				let image = UserData.more_game.image;
				if(!image){
					image = UserData.more_game.preview_image;
				}
				platform.previewImage({ urls: [image] });
				}
		}
		
	}
	private moreGameComplete(res){
		if(!Utils.callWXSuccess(res)){
			let url = UserData.more_game.preview_image ;
			if(!url){
				url = UserData.more_game.image;
			} 
			platform.previewImage({ urls: [url]});
		}else{
			
		}
	}

	//分享
	private shareGame() {
		// 策略A
		let query = {from:GameConfig.shareFrom.homePage2Share};
		let shareData = GameConfig.getShareData(GameConfig.shareInfoA,query);
		platform.shareAppMessage(shareData);
	}

	//开始游戏
	private startGame(evt:egret.TouchEvent) {
		if(evt.type == egret.TouchEvent.TOUCH_END){
			App.EventManager.dispatchEvent(GameConstants.UI_REMOVE_FROM_PARENT, this.index);
			App.EventManager.dispatchEvent(GameConstants.UI_ADD_TO_PARENT, GameConfig.uiIndex.game);
		}
		
	}

	//排行榜
	private ranklist(){
		App.EventManager.dispatchEvent(GameConstants.UI_ADD_TO_PARENT, GameConfig.uiIndex.rankListFromHome);
	}

	//群排行榜
	private groupRanklist(){
		// 策略F
		// 没有shareTicket则需要分享到群里获得群的shareTicket
		let query = {from:GameConfig.shareFrom.homePageGroup2Share};
		let shareData = GameConfig.getShareData(GameConfig.shareInfoC,query);
		platform.shareAppMessage(shareData);
		
	}
}